package com.vastcom.springbootangular5.service.impl;

import com.vastcom.springbootangular5.model.User;
import com.vastcom.springbootangular5.repository.UserRepository;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class CustomUserDetailsService implements UserDetailsService {

    protected final Log LOGGER= LogFactory.getLog(getClass());

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;



    //根据用户名查找用户;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user=userRepository.findUserByUsername(s);
        if(user==null){
            throw new UsernameNotFoundException(String.format("No user found with username '%s'.",s));

        }
        else {
            return user;
        }
    }

    public void changePassword(String oldPassword,String newPassword){
        Authentication  currentUser= SecurityContextHolder.getContext().getAuthentication();
       String username=currentUser.getName();
       if(authenticationManager!=null){
           LOGGER.debug("Re-authenticating user '"+ username + "' for password change request.");
       }
       else {
           LOGGER.debug("No authentication manager set. can't change Password!");

           return;
       }

        LOGGER.debug("Changing password for user '"+ username + "'");
       User user=(User) loadUserByUsername(username);
       user.setPassword(passwordEncoder.encode(newPassword));
       userRepository.save(user);


    }


}
